<?php

// Model:'ChucDanh' - Database Table: 'ChucDanh'

Class ChucDanh extends Eloquent {

    //Bang trong csdl
    private $nameTable = 'chuc_danh';
    //Rang buoc du lieu
    private $rules = array(
        'tencd' => 'required|min:3|max:60'
    );
    //So chức vụ hien thi tren mot trang
    private $chucdanh = 6;

    //Ham kiem tra du lieu
    public function validation($data) {
        return Validator::make($data, $this->rules);
    }

    //Lay so du lieu hien thi tren trang
    public function GetCHUCDANH() {
        return $this->chucdanh;
    }

    //Lay ds du lieu
    public function GetList($key) {
        $data = null;
        if ($key == null) {
            $data = DB::table($this->nameTable)
                    ->select("*")
                    ->orderBy("TEN_CD")
                    ->paginate($this->chucdanh);
        } else {
            $data = DB::table($this->nameTable)
                    ->select("*")
                    ->orWhere("TEN_CD", "LIKE", "%" . $key . "%")
                    ->orderBy("TEN_CD")
                    ->paginate($this->chucdanh);
        }

        return $data;
    }

    //Lay du lieu xac dinh
    public function GetOne($id) {
        return DB::table($this->nameTable)
                        ->select("*")
                        ->where("ID", $id)
                        ->first();
    }

    //
    public function GetWithTENCD($tencd) {
        return DB::table($this->nameTable)
                        ->select("*")
                        ->where("TEN_CD", $tencd)
                        ->first();
    }

    //Luu du lieu moi
    public function SaveIn($data) {
        $check = DB::table($this->nameTable)
                ->select("ID")
                ->where("TEN_CD", $data["TEN_CD"])
                ->first();
        if ($check == null) {
            return DB::table($this->nameTable)
                            ->insert($data);
        } else {
            return false;
        }
    }

    //Luu du lieu sua doi
    public function StoreIn($data, $id) {
        $check = DB::table($this->nameTable)
                ->select("*")
                ->where("TEN_CD", $data["TEN_CD"])
                ->where("ID", "<>", $id)
                ->first();
        if (!is_null($check)) {
            return false;
        } else {
            return DB::table($this->nameTable)
                            ->where("ID", $id)
                            ->update($data);
        }
    }

    //Xoa du lieu xac dinh
    public function Remove($id) {
        try {
            return DB::table($this->nameTable)
                            ->delete($id);
        } catch (Exception $ex) {
            return false;
        }
    }

}
